package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.PurchasePlanMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.IProductService;
import com.example.crossborderecommerce.service.IPurchasePlanService;
import com.example.crossborderecommerce.service.IStoreService;
import com.example.crossborderecommerce.service.impl.ProductServiceImpl;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购计划模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/purchase-plan")
public class PurchasePlanController {
    @Resource
    IPurchasePlanService purchasePlanService;
    @Resource
    PurchasePlanMapper purchasePlanMapper;
    @Resource
    IAdminService adminService;
    @Resource
    IStoreService storeService;
    @Resource
    IProductService productService;

    /**
     * 添加采购计划
     * @param purchasePlan
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody PurchasePlan purchasePlan) {
        boolean res = purchasePlanService.save(purchasePlan);
        if(res) {
            return Result.success("添加采购计划成功！");
        }
        return Result.error("添加采购计划失败！");
    }

    /**
     * 查询所有采购计划
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<PurchasePlan> purchasePlanList = purchasePlanService.list();
        if(purchasePlanList != null) {
            return Result.success("查询所有采购计划成功！", purchasePlanList);
        }
        return Result.error("查询所有采购计划失败！");
    }

    /**
     * 删除采购计划
     * @param purchasePlan
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody PurchasePlan purchasePlan) {
        boolean res = purchasePlanService.removeById(purchasePlan);
        if(res) {
            return Result.success("删除采购计划成功！");
        }
        return Result.error("删除采购计划失败！");
    }

    /**
     * 删除一系列采购计划
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> purchasePlanIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = purchasePlanService.removeByIds(purchasePlanIds);
        if(res) {
            return Result.success("删除采购计划成功");
        }
        return Result.error("删除采购计划失败！");
    }

    /**
     * 修改采购计划
     * @param purchasePlan
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody PurchasePlan purchasePlan) {
        boolean res = purchasePlanService.saveOrUpdate(purchasePlan);
        if (res) {
            return Result.success("修改采购计划成功！");
        }
        return Result.error("修改采购计划失败！");
    }

    /**
     * 分页查询所有的采购订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam(defaultValue = "-1") String storeId,
                           @RequestParam(defaultValue = "全部") String status,
                           @RequestParam(defaultValue = "") String productName,
                           @RequestParam(defaultValue = "") String timeFrom,
                           @RequestParam(defaultValue = "") String timeTo,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<PurchasePlan> purchasePlanPage = new Page<>(pageNum, pageSize);
        List<PurchasePlan> purchasePlanList = purchasePlanMapper.getPurchasePlanByPage(purchasePlanPage, adminId, storeId, status, productName, timeFrom, timeTo);
        for(PurchasePlan purchasePlan : purchasePlanList) {
            if(purchasePlan.getAdminId() != null) {
                Admin admin = adminService.getById(purchasePlan.getAdminId());
                purchasePlan.setAdminName(admin.getName());
            }
            if(purchasePlan.getStoreId() != null) {
                Store store = storeService.getById(purchasePlan.getStoreId());
                purchasePlan.setStoreName(store.getName());
            }
            if(purchasePlan.getProductId() != null) {
                Product product = productService.getById(purchasePlan.getProductId());
                purchasePlan.setProductName(product.getName());
            }
        }
        Page<PurchasePlan> newPurchasePlanPage = new Page<>(pageNum, pageSize);
        newPurchasePlanPage.setRecords(purchasePlanList);
        newPurchasePlanPage.setTotal(purchasePlanPage.getTotal());
        return Result.success("成功查询所有采购计划！",newPurchasePlanPage);
    }
    /**
     * 导出采购计划
     * @param response
     * @return
     */
    @GetMapping("exportPurchasePlanList")
    public Result exportPurchasePlanList(@RequestParam(defaultValue = "-1") String adminId,
                                         @RequestParam(defaultValue = "-1") String storeId,
                                         @RequestParam(defaultValue = "全部") String status,
                                         @RequestParam(defaultValue = "") String productName,
                                         @RequestParam(defaultValue = "") String timeFrom,
                                         @RequestParam(defaultValue = "") String timeTo,
                                         HttpServletResponse response) {
        QueryWrapper<PurchasePlan> queryWrapper = new QueryWrapper<>();
        List<PurchasePlan> purchasePlanList = purchasePlanService.list(queryWrapper);
        for(PurchasePlan purchasePlan : purchasePlanList) {
            if(purchasePlan.getAdminId() != null) {
                Admin admin = adminService.getById(purchasePlan.getAdminId());
                purchasePlan.setAdminName(admin.getName());
            }
            if(purchasePlan.getStoreId() != null) {
                Store store = storeService.getById(purchasePlan.getStoreId());
                purchasePlan.setStoreName(store.getName());
            }
            if(purchasePlan.getProductId() != null) {
                Product product = productService.getById(purchasePlan.getProductId());
                purchasePlan.setProductName(product.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("产品");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("采购数量");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("仓库");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("计划金额");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("计划采购时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("负责人");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("状态");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < purchasePlanList.size(); i++) {
            row = sheet.createRow(i + 1);
            PurchasePlan purchasePlan = purchasePlanList.get(i);
            row.createCell((short) 0).setCellValue(purchasePlan.getId());
            row.createCell((short) 1).setCellValue(purchasePlan.getProductName());
            row.createCell((short) 2).setCellValue(purchasePlan.getQuantity());
            row.createCell((short) 3).setCellValue(purchasePlan.getStoreName());
            row.createCell((short) 4).setCellValue(purchasePlan.getPrice());
            row.createCell((short) 6).setCellValue(purchasePlan.getAdminName());
            row.createCell((short) 7).setCellValue(purchasePlan.getStatus());
            try {
                Date planTime = inputDateFormat.parse(purchasePlan.getPlanTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 5).setCellValue(outputDateFormat.format(planTime));
            } catch (ParseException e) {
                row.createCell((short) 5).setCellValue(purchasePlan.getPlanTime().toString());
            }
        }
        String fileName = "exportPurchasePlanList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }

}
